<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
function p($data, $is_die=true) {
	// http_response_code(500);
    echo '<pre>';
    print_r($data);
    echo '</pre>';
    if($is_die == true) {
        die;
    }
}

function arrayToQueryString($array){
	$str = '';
	if(!is_array($array)||empty($array))
		return $str;
	foreach($array as $key => $value):
		$str .= '&'.$key.'='.$value;
	endforeach;
	return $str;
}

function hashPwd($pwd){
	return password_hash($pwd,PASSWORD_DEFAULT);
}

/**
 * 从数组中选出指定键值对的数据
 * @param  [type] $array [description]
 * @param  [type] $key   [description]
 * @param  [type] $value [description]
 * @return [type]        [description]
 */
function sameKeyValueArray($array,$where){
	$data = [];
	foreach($array as $value):
		$flag = true;
		foreach($where as $k => $v):
			if(isset($value[$k])){
				if($value[$k]!=$v){
					$flag = false;
				}
			}else{
				$flag = false;
			}
		endforeach;
		if($flag){
			$data[] = $value;
		}
	endforeach;
	return $data;
}

/**
 * 将数组中键值唯一的值作为键组成新数组
 * @param  [type] $array [description]
 * @param  [type] $key   [description]
 * @return [type]        [description]
 */
function arrayValueToKey($array,$key){
	$return = [];
	foreach($array as $value):
		$return[$value[$key]] = $value;
	endforeach;
	return $return;
}

/**
 * 将请求转成query string
 * @param  [type] $array [请求]
 * @param  [type] $limit [限制字段]
 * @return [type]        [description]
 */
function parseQuery($array,$limit=[]){
    $where=[];
    if($limit):
	    foreach($limit as $v):
	        if(isset($array[$v])){
	            $where[$v] = $array[$v];
	        }
	    endforeach;
    else:
    	$where = $array;
    endif;
    // 数组转成字符串
    $queryStr = arrayToQueryString($where);
    $queryStr = ltrim($queryStr,'&');
    return $queryStr;
}

/**
 * 生成一个随机的字符串
 *
 * @param int $length
 * @param boolean $special_chars
 * @return string
 */
function getRandStr($length = 12, $special_chars = true) {
	$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	if ($special_chars) {
		$chars .= '!@#$%^&*()';
	}
	$randStr = '';
	for ($i = 0; $i < $length; $i++) {
		$randStr .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
	}
	return $randStr;
}

/**
 * 分页函数
 * @param  [type] $total    [description]
 * @param  [type] $perNum   [description]
 * @param  [type] $page     [description]
 * @param  [type] $baseUrl  [description]
 * @param  string $queryStr [description]
 * @return [type]           [description]
 */
function pagination($total, $perNum, $page, $baseUrl, $queryStr = '') {
	$pageNums = @ceil($total / $perNum);
	$html = '';

	if($pageNums>=7){

		$html .= '<a href="'.$baseUrl.$queryStr.'" class="first">首页</a>';

		for($i=1;$i<=$pageNums;$i++){

			if($i==($page-4)&&$i>=1){
				$html .= '<span>...</span>';
			}

			if($i<=$page+3 && $i>=$page-3){

				if($i==$page){
					$btn = '<a class="current">'.$i.'</a>';
				}else{
					$btn = '<a href="'.$baseUrl.'?page='.$i.$queryStr.'">'.$i.'</a>';
				}
				$html .= $btn;
			}

			if($i==($page+4)&&$i<=$pageNums){
				$html .= '<span>...</span>';
			}

		}

		$html .= '<a href="'.$baseUrl.'?page='.$pageNums.$queryStr.'" class="last">尾页</a>';

	}else{
		for($i=1;$i<=$pageNums;$i++){
			if($i==$page){
				$btn = '<a class="current">'.$i.'</a>';
			}else{
				$btn = '<a href="'.$baseUrl.'?page='.$i.$queryStr.'">'.$i.'</a>';
			}
			$html .= $btn;
		}
	}

	return $html;
}

/**
 * 查询参数解析
 * @param  [type] $where [description]
 * @return [type]        [description]
 */
function parseWhere($where,$has_mid=false){
	$array = [];
	foreach($where as $key => $value):
		if(!$value)
			continue;
		switch ($key) {
			case 'mid':
				$array[$key] = ['like','%'.$value.'%'];
				if(!$has_mid){
            		$result = model('member')->where(['mid'=>['exp',"like '%".$value."%'"]])->field('id')->select();
                    $ids = [];
                    foreach($result as $uid):
                    	$ids[]=$uid['id'];
                    endforeach;
                    unset($array[$key]);
                    $array['uid'] = ['in',$ids];
            	}else{
            		$array[$key] = ['like','%'.$value.'%'];
            	}
				break;
			case 'mname':
				$array[$key] = ['like','%'.$value.'%'];
				break;
			case 'start':
				$array['create_time'] = ['>=',strtotime($value)];
				break;
			case 'end':
				$array['create_time'] = ['<=',strtotime($value)];
				break;
			default:
				$array[$key] = $value;
				break;
		}
	endforeach;

	if(isset($where['start'])&&isset($where['end'])){
		if(!empty($where['start'])&&!empty($where['end'])){
			$array['create_time'] = ['between', [strtotime($where['start']),strtotime($where['end'])]];
				//'between time' => [strtotime($where['start']),strtotime($where['end'])]
			
		}
	}
	return $array;
}
/**
 * 去除数组空值项
 * @return [type] [description]
 */
function filterArrEmptyItem($array){
	foreach($array as $key => $value):
		if(empty($value)):
			unset($array[$key]);
		endif;
	endforeach;
	return $array;
}
/**
 * 导出exccel
 * @param  [type] $filename [description]
 * @param  [type] $content  [description]
 * @return [type]           [description]
 */
function exportExcel($filename,$content){

 	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	header("Content-Type: application/vnd.ms-execl");
	header("Content-Type: application/force-download");
	header("Content-Type: application/download");
    header("Content-Disposition: attachment; filename=".$filename);
    header("Content-Transfer-Encoding: binary");
    header("Pragma: no-cache");
    header("Expires: 0");

    echo $content;
    exit;
}
/**
 * 过滤html
 * @param  [type] $v    [description]
 * @param  [type] $rule [description]
 * @param  [type] $data [description]
 * @return [type]       [description]
 */
function filterHtml($v){
    $config = \HTMLPurifier_Config::createDefault();
    $purifier = new \HTMLPurifier($config);
    $clean_html = $purifier->purify($v);
    return $clean_html;
}

function create_guid()
{
return uniqid('wx_',true).'_'.rand(10000,99999);
}

function upload($file_name)
{
    $file_list = request()->file($file_name);
    $info_list = [];
    foreach($file_list as $v){
        if(!$info = $v->move(UPLOAD_PATH)){
            return [
                'code'  =>  0,
                'msg'   =>  $v->getError()
            ];
        }
        $info_list[] = $info;
    }
    return [
        'code'  =>  1,
        'msg'   =>  $info_list
    ];
}